<template>
  <div class="detail" ref="containerRef">
    <a-affix :target="(containerRef as HTMLElement)">
      <a-page-header title="取消" @back="back" class="head">
        <template #extra v-if="approveStatus == 'edit'">
          <a-space align="center" class="header-right">
            <a-link @click="openOraginal">
              <template #default>原文</template>
            </a-link>
            <a-form-item style="margin: 0 0 0 12px" field="status" label="改写模型">
              <a-select disabled v-model="currentModel" placeholder="请选择" allow-clear>
                <a-option value="-1">星火</a-option>
              </a-select>
            </a-form-item>
          </a-space>
        </template>
      </a-page-header>
    </a-affix>
    <div class="detail-container">
      <icon-expand class="expand-icon expand-left" size="18" v-show="!expand.left" @click="expand.left = true" />
      <div class="slider-box left" @click="expand.left = false" v-show="expand.left">
        <icon-shrink size="18" />
        <div class="slider-title">{{ process.name }}</div>
        <div class="item-title">完全通过率：</div>
        <a-progress color="#54bcbd" size="large" :percent="process.pass" />
        <div class="item-title">微改率：</div>
        <a-progress color="orange" size="large" :percent="process.edit" />
        <div class="item-title">不可用率：</div>
        <a-progress color="#de868f" size="large" :percent="process.reject" />
      </div>
      <!-- 原文显示 -->
      <div class="original" v-show="showOraginal">
        <a-space style="justify-content: space-between; width: 100%">
          <a-form-item style="margin: 0" field="title" :label="titleText">
            <span class="title-text">{{ articalTitle }}</span>
          </a-form-item>
          <icon-close @click="closeOraginal" class="close-icon" size="18" />
        </a-space>
        <a-resize-box
          :directions="['right']"
          :style="{
            width: '800px',
            minWidth: '100px',
            maxWidth: '100%',
            height: 'calc(100% - 40px)'
          }"
        >
          <div class="original-text" v-html="textContet"></div>
          <!-- <iframe :srcdoc="textContet" width="100%" height="100%" frameborder="0" allowfullscreen></iframe> -->
        </a-resize-box>
      </div>
      <div class="content">
        <div class="artical-title">
          <a-form-item field="title" :label="titleText">
            <a-input
              style="width: 100%"
              size="small"
              v-if="type === 'audit' && approveStatus == 'edit'"
              v-model="articalTitleEdit"
              placeholder="请输入"
            />
            <span class="title-text" v-if="type === 'view' || approveStatus == 'view'">{{ articalTitle }}</span>
          </a-form-item>
        </div>
        <div class="article-content">
          <editor
            ref="editorRef"
            v-model="editContet"
            v-if="type === 'audit' && approveStatus == 'edit'"
            style="width: 100%; height: 100%"
          ></editor>
          <!-- v-html="editContet" -->
          <div class="view-info" v-if="type === 'view' || approveStatus == 'view'" v-html="editContet"></div>
          <!-- <iframe :srcdoc="editContet" width="100%" height="100%" frameborder="0" allowfullscreen></iframe> -->
        </div>
      </div>
      <div class="slider-box right" v-show="expand.right">
        <icon-shrink size="18" @click="expand.right = false" />
        <a-tabs v-model="currentTab" size="small">
          <a-tab-pane key="0" title="原始图库">
            <a-scrollbar>
              <!-- 原始图库 -->
              <a-image
                @click="handleClickImage(item.url)"
                style="cursor: pointer"
                :preview="false"
                :draggable="false"
                fit="contain"
                v-for="item in originImage"
                width="100%"
                height="200px"
                :src="item.url"
              />
            </a-scrollbar>
          </a-tab-pane>
          <a-tab-pane key="1" title="相似图库">
            <a-scrollbar>
              <!-- <img
            @click="handleClickImage(item.url)"
            style="width: 100%; height: 200px; object-fit: contain"
            v-for="item in picArr"
            :src="item.url"
            alt=""
          /> -->
              <a-image
                @click="handleClickImage(item.url)"
                style="cursor: pointer"
                :preview="false"
                :draggable="false"
                fit="contain"
                v-for="item in picArr"
                width="100%"
                height="200px"
                :src="item.url"
              />
            </a-scrollbar>
          </a-tab-pane>
        </a-tabs>
      </div>
      <icon-expand class="expand-icon expand-right" size="18" v-show="!expand.right" @click="expand.right = true" />
    </div>
    <div class="detail-footer" v-if="type === 'audit'">
      <a-form-item field="push_system" label="推送平台">
        <a-cascader
          disabled
          style="width: 300px"
          :options="pushSystemOptions"
          v-model="push_system"
          placeholder="请选择"
          allow-clear
        />
      </a-form-item>
      <div class="operation-button" v-show="currentAritical?.status == '-1' || currentAritical?.status == '0'">
        <a-button @click="handlepass('passEdit')" type="primary" v-if="approveStatus == 'edit'">
          <template #default>确定通过</template>
        </a-button>
        <a-button type="primary" v-else @click="handlepass('pass')">
          <template #default>完全通过</template>
        </a-button>
        <a-button
          v-show="currentAritical?.status != '-1'"
          @click="visible = true"
          v-if="approveStatus == 'edit'"
          class="mgl-12"
          type="primary"
        >
          <template #default>放弃修改</template>
        </a-button>
        <a-button v-else @click="approveStatus = 'edit'" class="mgl-12" type="primary">
          <template #default>微改</template>
        </a-button>
        <a-button
          v-if="approveStatus == 'edit'"
          @click="
            () => {
              approveStatus = 'view'
              showOraginal = false
              expand.left = true
              expand.right = true
            }
          "
          class="mgl-12"
          type="primary"
        >
          <template #default>返回上级</template>
        </a-button>
        <a-button v-show="currentAritical?.status != '-1'" v-else @click="visible = true" class="mgl-12" type="primary">
          <template #default>不可用</template>
        </a-button>
      </div>
      <!-- <div class="message-box">
        <div class="message-info" v-show="second > 0">
          <span style="color: red">{{ second }}秒</span>
          后推送到后台
          <icon-undo @click="handleCancel" />
        </div>
      </div> -->
    </div>
    <!-- 微改确认弹窗 -->
    <a-modal :width="250" v-model:visible="visible" :footer="false">
      <template #title> 选择不可用原因 </template>
      <a-radio-group v-model="reason" @change="handleChangeReason">
        <a-grid :cols="1" :colGap="24" :rowGap="16">
          <a-grid-item v-for="(item, key) in resonOption">
            <a-radio :value="key">{{ item }}</a-radio>
          </a-grid-item>
        </a-grid>
      </a-radio-group>
    </a-modal>
  </div>
</template>

<script setup lang="ts" name="DataDetail">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import {
  getPushSystem,
  getAuditList,
  getTemplateDetail,
  getPictureList,
  trashStatus,
  pushStatus,
  epushStatus
} from '@/apis'
import editor from './components/editor.vue'
import { useAppStore } from '@/stores'
import eventBus from '@/utils/eventBus'

const appStore = useAppStore()
const currentTab = ref('0')
const originImage = ref([])
const editorRef = ref(null)
const editContet = ref('')
const textContet = ref('')
const articalTitleEdit = ref('')
const articalTitle = ref('')
const approveStatus = ref('view')
const expand = reactive({
  left: true,
  right: true
})
const process = reactive({
  name: '模板名称',
  pass: 0,
  edit: 0,
  reject: 0
})
const picArr = ref([])
const currentModel = ref('-1')
const visible = ref(false)
const route = useRoute()
const router = useRouter()
let aritcleId = route.query.id
const type = route.query.type
const articleType = route.query.articleType
const titleText = ref('文章标题')
if (articleType == '2') {
  titleText.value = '资讯标题'
} else {
  titleText.value = '文章标题'
}
const containerRef = ref<HTMLElement | null>()
const back = () => {
  // handleCancel()
  router.back()
}
// 获取联级菜单选项
// 树形遍历
const push_system = ref([])
function transformTree(data) {
  return data.map((node) => ({
    value: node.id,
    label: node.name,
    children: node?.child?.length > 0 ? transformTree(node.child) : null
  }))
}
const pushSystemOptions = ref([])
const getPushSystemOptions = async () => {
  const resData = await getPushSystem()

  if (resData.code == 1) {
    let system_channel = resData.data.system_channel || []
    pushSystemOptions.value = resData.data.push_system.map((dd) => {
      let isHave = system_channel.findIndex((cc) => cc.push_system_id === dd.id)
      let children = null
      if (isHave !== -1) {
        let temp = system_channel.filter((cc) => cc.push_system_id === dd.id)
        children = transformTree(temp)
      }
      return {
        value: dd.id,
        label: dd.name,
        children
      }
    })
  }
}
getPushSystemOptions()
const reason = ref('')
const handleChangeReason = (e) => {
  visible.value = false
  handleTrash()
}
const showOraginal = ref(false)
const openOraginal = () => {
  showOraginal.value = true
  expand.left = false
  expand.right = true
}
const closeOraginal = () => {
  showOraginal.value = false
  expand.left = true
  expand.right = true
}
// const second = ref(1)
// let timer = null
const setSecond = (type) => {
  if (appStore.withdrawSecond > 0) {
    let timerT = setTimeout(() => {
      appStore.setWithdrawSecond(appStore.withdrawSecond - 1)
      setSecond(type)
    }, 1000)
    appStore.setwithdrawTimer(timerT)
  } else {
    if (appStore.withdrawTimer) {
      if (type === 'pass') {
        handlePush()
      } else {
        handleEpush()
      }
    }
    clearTimeout(appStore.withdrawTimer)
    appStore.setwithdrawTimer(null)
  }
}
// const handleCancel = () => {
//   second.value = 0
//   clearTimeout(timer)
//   timer = null
// }
const handlepass = (type) => {
  // 如果点击太快
  if (appStore.withdrawTimer) {
    Message.warning('请勿频繁点击!')
    return
  }
  if (type == 'passEdit' && !articalTitleEdit.value) {
    Message.error(`请输入${titleText.value}！`)
    return
  }
  // 将当前信息存入全局store
  appStore.setLastPageData({
    aritcleId: aritcleId,
    editContet: editContet.value,
    articalTitleEdit: articalTitleEdit.value
  })
  // second.value = 3
  appStore.setWithdrawSecond(3)
  // 直接到下一篇
  // 重置状态
  approveStatus.value = 'view'
  closeOraginal()
  if (currentAritical.value.status === '-1') {
    setTimeout(() => {
      router.back()
    }, 500)
  } else {
    getTableData()
  }

  setSecond(type)
}
// 获取下一篇未审批文章
const getTableData = async () => {
  const resData = await getAuditList({
    page: 1,
    pagesize: 10,
    status: '0',
    type: articleType
  })

  if (resData.code == 1) {
    let otherArr = (resData.data.data.data || []).filter((dd) => dd.id != aritcleId)
    if (otherArr.length > 0) {
      let nexpage = otherArr?.[0] || {}
      router.replace({ path: '/audit-management/approve-page', query: { id: nexpage.id, type, articleType } })
      aritcleId = nexpage.id
      resetInfo()
    } else {
      Message.error(resData.msg || '没有下一篇未审批文章')
    }
  } else {
  }
}
const currentAritical = ref()
const initCurrentData = async () => {
  const resData = await getAuditList({
    page: 1,
    pagesize: 1,
    post_id: aritcleId
  })
  const current = resData.data?.data?.data?.[0] || {}
  currentAritical.value = current
  textContet.value = current.content
  editContet.value = current.content
  articalTitleEdit.value = current.title
  articalTitle.value = current.title
  let template_id = current.template_id
  push_system.value = current.system_channel_id ?? current.push_system
  // 原始图库
  if (current.images) {
    originImage.value = current.images
      .split(',')
      .filter((dd) => dd)
      .map((dd) => {
        return {
          url: dd
        }
      })
  }

  //调用模板查询接口
  templateDetail(template_id)
  // 查询相似图库
  initImage(current.keywords)
}
const imagePage = reactive({
  page: 1,
  pageSize: 10
})
const initImage = async (keyword) => {
  const resData = await getPictureList({
    page: imagePage.page,
    pagesize: imagePage.pageSize,
    keyword: keyword
  })
  console.log(resData)
  picArr.value = (resData.data?.data || []).map((dd) => {
    return {
      ...dd,
      url: dd.image
    }
  })
}
const templateDetail = async (id) => {
  let res = await getTemplateDetail({ template_id: id })
  if (res.code == 0) {
    Message.error(res.msg || '获取详情失败')
    return
  }
  console.log(res)
  process.name = res.data.name
  const passNum = res.data?.complete_num || 0
  const editNum = res.data?.small_edit_num || 0
  const rejectNum = res.data?.trash_num || 0
  const totalNum = passNum + editNum + rejectNum
  if (totalNum === 0) return
  process.pass = (passNum / totalNum).toFixed(4)
  process.edit = (editNum / totalNum).toFixed(4)
  process.reject = (rejectNum / totalNum).toFixed(4)
}
const resonOption = {
  A: '字数不达标',
  B: '出现敏感词',
  C: '首段语言不够精炼',
  D: '内容与关键词不符',
  E: '未回答标题内容',
  F: '文章格式与要求不符'
}
// 废弃
const handleTrash = async () => {
  const resData = await trashStatus({
    post_id: aritcleId,
    remark: resonOption[reason.value]
  })
  if (resData.code === 1) {
    Message.success(resData.msg || '操作成功！')
    setTimeout(() => {
      router.back()
    }, 500)
  } else {
    Message.error(resData.msg || '操作失败！')
  }
}
// 直接推送
const handlePush = async () => {
  const resData = await pushStatus({
    post_id: appStore.lastPageData.aritcleId
  })
  eventBus.$emit('handleChangeAudit')
  if (resData.code === 1) {
    Message.success(resData.msg || '操作成功！')
    // // 重置状态
    // approveStatus.value = 'view'
    // closeOraginal()

    // if (currentAritical.value.status === '-1') {
    //   setTimeout(() => {
    //     router.back()
    //   }, 500)
    // } else {
    //   getTableData()
    // }
  } else {
    Message.error(resData.msg || '操作失败！')
    // 后台返回失败后返回列表
    // if (resData.msg === '平台拒绝请求，推送失败') {
    //   setTimeout(() => {
    //     router.back()
    //   }, 500)
    // }
  }
}
// 编辑后推送

const handleEpush = async () => {
  const formData = new FormData()
  formData.append('post_id', appStore.lastPageData.aritcleId)
  formData.append('content', appStore.lastPageData.editContet)
  formData.append('title', appStore.lastPageData.articalTitleEdit)
  const resData = await epushStatus(formData)
  eventBus.$emit('handleChangeAudit')
  if (resData.code === 1) {
    Message.success(resData.msg || '操作成功！')
    // // 重置状态
    // approveStatus.value = 'view'
    // closeOraginal()
    // if (currentAritical.value.status === '-1') {
    //   setTimeout(() => {
    //     router.back()
    //   }, 500)
    // } else {
    //   getTableData()
    // }
  } else {
    Message.error(resData.msg || '操作失败！')
    // if (resData.msg === '平台拒绝请求，推送失败') {
    // setTimeout(() => {
    //   router.back()
    // }, 500)
    // }
  }
}
const handleClickImage = (val) => {
  if (!val) return
  editorRef.value?.handleSertPic(val)
}
const resetInfo = () => {
  initCurrentData()
  imagePage.page = 1
  imagePage.pageSize = 10
  visible.value = false
  reason.value = ''
  showOraginal.value = false
  closeOraginal()
}
onMounted(() => {
  initCurrentData()
})
</script>

<style lang="scss" scoped>
.detail {
  overflow: auto;
  height: 100%;
  .head {
    background: var(--color-bg-1);
  }
  .item {
    margin: $margin;
    background: var(--color-bg-1);
    border-radius: 2px;
  }
  .detail-container {
    height: calc(100% - 174px);
    background: var(--color-bg-1);
    margin: 20px;
    display: flex;
    position: relative;
    .expand-icon {
      // position: absolute;
      cursor: pointer;
      padding: 4px;
      border: 1px solid var(--color-border);
      border-radius: 4px;
    }
    .expand-left {
      transform: rotate(90deg);
    }
    .expand-right {
      right: 0;
    }
    .original {
      // flex: 1;
      box-shadow: 0 2px 4px 2px rgba(0, 0, 0, 0.08);
      padding: 16px;
      line-height: 20px;
      .original-text {
        width: 100%;
        height: 100%;
        overflow: auto;
        white-space: break-spaces;
      }
      .close-icon {
        cursor: pointer;
      }
    }
    .view-info {
      padding: 16px;
      line-height: 20px;
      box-sizing: border-box;
      white-space: break-spaces;
    }
    .slider-box {
      width: 300px;
      box-shadow: 0 2px 4px 2px rgba(0, 0, 0, 0.08);
      position: relative;
      padding: 20px 12px;
      box-sizing: border-box;
      svg {
        position: absolute;
        cursor: pointer;
        top: 0;
      }
      .slider-title {
        text-align: center;
        color: #999;
        font-weight: bold;
        font-size: 16px;
      }
      .item-title {
        font-size: 14px;
        color: #333;
        font-weight: bold;
        margin-top: 30px;
        margin-bottom: 8px;
      }
    }
    .left {
      svg {
        position: absolute;
        right: 0;
        transform: rotate(90deg);
      }
    }
    .right {
      svg {
        left: 0;
      }
      .arco-tabs {
        height: 100%;
        :deep(.arco-tabs-content) {
          height: calc(100% - 36px);
          .arco-tabs-content-list {
            height: 100%;
            .arco-tabs-pane {
              height: 100%;
            }
          }
        }
      }
      .arco-scrollbar {
        height: 100%;
        overflow: auto;
        .arco-image {
          margin-bottom: 12px;
        }
      }
    }
    .content {
      flex: 1;
      padding: 12px;
      .artical-title {
        width: 100%;
        height: 32px;
        line-height: 32px;
        .title-text {
          font-weight: bold;
          display: inline-block;
          max-width: 600px;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
      .article-content {
        width: 100%;
        height: calc(100% - 40px);
        margin-top: 8px;
        .view-info {
          height: calc(100% - 40px);
          overflow: auto;
        }
      }
    }
  }
  .detail-footer {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    padding: 10px;
    .operation-button {
      justify-self: center;
    }
    .mgl-12 {
      margin-left: 12px;
    }
    // .message-box {
    //   justify-self: end;
    //   .message-info {
    //     padding: 4px;
    //     background: #fff;
    //     box-shadow: 0 2px 4px 2px rgba(0, 0, 0, 0.08);
    //     border-radius: 4px;
    //     .arco-icon {
    //       color: blue;
    //       cursor: pointer;
    //     }
    //   }
    // }
  }
}
</style>
